package com.wantup.demo01;

import java.util.Map;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/6/25 13:06
 */
public class TestCompareAndSwap {

    public static void main(String[] args) {
        CompareAndSwap andSwap = new CompareAndSwap();

        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int value = andSwap.getValue();
                    int newValue = (int) (Math.random() * 100);
                    System.out.println("value " + value + "  newValue  " + newValue);
                    boolean bool = andSwap.compareAndSet(value, newValue);
                    System.out.println(bool);
                }
            }).start();
        }

    }

}

class CompareAndSwap {
    //内存中的值
    private int value;

    //获取值
    public synchronized int getValue() {
        return value;
    }

    //比较 预估值和新值是否相等
    public synchronized int compareAndSwap(int expecteValue, int newValue) {
        int oldValue = getValue();
        if (oldValue == expecteValue) {
            this.value = newValue;
        }
        return oldValue;
    }

    public synchronized boolean compareAndSet(int expecteValue, int newValue) {
        return expecteValue == compareAndSwap(expecteValue, newValue);
    }

}


